package com.sbtr.security.common.security;

import cn.hutool.json.JSONUtil;
import com.sbtr.security.common.constant.JwtConstant;
import com.sbtr.security.entity.CheckResult;
import com.sbtr.security.entity.R;
import com.sbtr.security.entity.SysUser;
import com.sbtr.security.service.SysUserService;
import com.sbtr.security.util.JwtUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private MyUserDetailServiceImpl myUserDetailService;

    @Autowired
    private SysUserService sysUserService;

//    public JwtAuthenticationFilter(AuthenticationManager authenticationManager) {
//        super(authenticationManager);
//    }
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        String token = request.getHeader("token");
        if(true){
            chain.doFilter(request,response);
            return;
        }

//        System.out.println("请求路径："+request.getRequestURI());
//        if(StringUtils.isBlank(token)||new ArrayList<>(Arrays.asList(SecurityConfig.URL_WHITELIST)).contains(request.getRequestURI())){
        if("null".equals(token)||token==null|| SecurityContextHolder.getContext().getAuthentication()!=null){
            chain.doFilter(request,response);
            return;
        }

        CheckResult checkResult = JwtUtils.validateJWT(token);
        if(!checkResult.isSuccess()){
            ServletOutputStream outputStream = response.getOutputStream();

            switch (checkResult.getErrCode()){
                case JwtConstant.JWT_ERRCODE_NULL:
                    outputStream.write(JSONUtil.toJsonStr(R.error(JwtConstant.ERR_CODE,"Token不存在！")).getBytes(StandardCharsets.UTF_8));
                    break;
                case JwtConstant.JWT_ERRCODE_FAIL:
                    outputStream.write(JSONUtil.toJsonStr(R.error(JwtConstant.ERR_CODE,"Token验证不通过！")).getBytes(StandardCharsets.UTF_8));
                    break;
                case JwtConstant.JWT_ERRCODE_EXPIRE:
                    outputStream.write(JSONUtil.toJsonStr(R.error(JwtConstant.ERR_CODE,"Token过期！")).getBytes(StandardCharsets.UTF_8));
                    break;
            }
            return;
        }


        Claims claims = JwtUtils.parseJWT(token);
        String username = claims.getSubject();

        SysUser sysUser = sysUserService.getByUserName(username);

        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken=new UsernamePasswordAuthenticationToken(username,null,myUserDetailService.getUserAuthority(sysUser.getId()));

        SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);

        chain.doFilter(request,response);

    }
}
